<?php

namespace app\common\command\algorithm;

class Bargain
{

    /**
     * 获取随机金额
     * Author   亓官雨树<lucky.max@foxmail.com>
     * DateTime 2021-04-12
     *
     * @param $remainNum    int     剩余次数
     * @param $remainMoney  float   剩余金额[第一次为后台配置的砍价金额]
     * @param $min          float
     * @return array    [随机金额, 剩余金额]
     */
    public function getBargainMoney($remainNum, $remainMoney, $min = 0.01): array
    {
        if (!$remainNum) return ['bargain_price' => 0, 'remain_price' => 0, 'remain_nums' => 0];
        if ($remainNum == 1) {//只剩一次，直接返回剩余金额
            return ['bargain_price' => $remainMoney, 'remain_price' => 0, 'remain_nums' => 0];
        }
        // 当前平均
        $avg = $remainMoney / $remainNum;
        // 最大金额为：（剩余金额/剩余次数）* 2 , 若当前平均不够最小值，取最小值
        $max = $avg <= $min ? $min : ($avg * 2);
        // 产生随机的金额
        $money = round($this->_randomFloat() * $max, 2);
        // 如果比要求的最小的金额还小，则取最小金额
        $money = max($min, $money) * 1;
        // 
        bcscale(2);
        $remainMoney = bcsub($remainMoney . '', $money . '');

        return ['bargain_price' => $money, 'remain_price' => $remainMoney, 'remain_nums' => $remainNum - 1];
    }

    /**
     * 获取一个随机的两位小数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-04-12
     *
     * @return [type] [description]
     */
    private function _randomFloat(): float
    {
        return round(mt_rand(1, 100) / 100, 2);
    }

}
